package com.lanxiao.cloud.modules.file.domain.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.IdUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.StorageClass;
import com.lanxiao.cloud.common.core.exception.BusinessException;
import com.lanxiao.cloud.common.core.utils.StringUtils;
import com.lanxiao.cloud.modules.file.domain.model.FileConfigure;
import com.lanxiao.cloud.modules.file.domain.service.IUploadFileService;
import com.lanxiao.cloud.modules.file.infrastructure.enums.UploadType;
import com.lanxiao.cloud.modules.file.infrastructure.error.UploadErrorType;
import java.io.IOException;
import java.io.InputStream;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author ：qiaoliang
 * @date ：2021-10-25
 */
@Service
public class AliyunUploadServiceImpl implements IUploadFileService {

  @Override
  public String uploadFile(MultipartFile file, FileConfigure fileConfigure) {
    // 创建OSSClient实例。
    OSS ossClient = new OSSClientBuilder().build(fileConfigure.getEndpoint(), fileConfigure.getAccessKey(), fileConfigure.getSecretKey());
    String uploadUrl = null;
    try {
      this.doesBucketExist(ossClient, fileConfigure.getBucket());
      InputStream inputStream = file.getInputStream();
      String filename = file.getOriginalFilename();
      BusinessException.isTrue(StringUtils.isBlank(filename), UploadErrorType.UPLOAD_ERROR);
      // 在文件名称中添加随机的唯一的值，防止名称一样时文件的覆盖
      String uuid = IdUtil.simpleUUID();
      // 文件类型
      String fileType = filename.substring(filename.lastIndexOf("."));
      filename = uuid + fileType;
      // 把文件安装日期进行分类，会自动创建文件夹
      String datePath = new DateTime().toString("yyyy-MM-dd");
      filename = datePath + "/" + filename;
      ossClient.putObject(fileConfigure.getBucket(), filename, inputStream);
      // 上传文件之后的路径，自己拼接
      uploadUrl = "http://" + fileConfigure.getBucket() + "." + fileConfigure.getEndpoint() + "/" + filename;

    } catch (IOException e) {
      e.printStackTrace();
      throw new BusinessException(UploadErrorType.UPLOAD_ERROR);
    } finally {
      // 关闭OSSClient。
      ossClient.shutdown();
    }
    return uploadUrl;
  }


  /**
   * 判断Bucket是否存在
   */
  public void doesBucketExist(OSS ossClient, String bucketName) {
    CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
    // 设置bucket权限为公共读，默认是私有读写
    createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
    // 设置bucket存储类型为低频访问类型，默认是标准类型
    createBucketRequest.setStorageClass(StorageClass.IA);
    if (!ossClient.doesBucketExist(bucketName)) {
      ossClient.createBucket(createBucketRequest);
    }
  }

  @Override
  public UploadType only() {
    return UploadType.ALIYUN;
  }

}
